package cn.wolfcode.cloud.zuulserver.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthZuulFilter extends ZuulFilter { //继承ZuulFilter
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }//过滤器类型:前置过滤

    @Override
    public int filterOrder() {
        return 1;
    } //过滤顺序

    @Override
    public boolean shouldFilter() {//过滤规则:对URL 进行判断
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if(request.getRequestURI().indexOf("order")>=0){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException { //过滤后的业务处理逻辑
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isEmpty(token)){
            requestContext.setSendZuulResponse(false); //不放行
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); //设置状态码
        }
        return null;
    }
}